package com.gs.spring.core.initializing;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;

public class ShutdownHookBean implements Runnable, BeanFactoryAware{

	ConfigurableListableBeanFactory factory;
	
	public ShutdownHookBean() {
	}
	
	public void run() {
		System.out.println("Destroying singletons");
		factory.destroySingletons();
	}

	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		if(beanFactory instanceof DefaultListableBeanFactory){
			this.factory = (ConfigurableListableBeanFactory)beanFactory;
			Runtime.getRuntime().addShutdownHook(new Thread(this));
		}
	}

}
